using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GoChat_for_Windows.Services;

namespace GoChat_for_Windows.ViewModels
{
    public partial class RegisterViewModel : ViewModelBase
    {
        private readonly INavigationService _navigationService;

        [ObservableProperty]
        private string username = string.Empty;

        [ObservableProperty]
        private string password = string.Empty;

        [ObservableProperty]
        private string confirmPassword = string.Empty;

        [ObservableProperty]
        private string nickname = string.Empty;

        public RegisterViewModel(IApiService apiService, INavigationService navigationService) 
            : base(apiService)
        {
            _navigationService = navigationService;
        }

        [RelayCommand]
        private async Task RegisterAsync()
        {
            if (string.IsNullOrWhiteSpace(Username) || 
                string.IsNullOrWhiteSpace(Password) || 
                string.IsNullOrWhiteSpace(ConfirmPassword) ||
                string.IsNullOrWhiteSpace(Nickname))
            {
                ErrorMessage = "请填写所有必填字段";
                return;
            }

            if (Password != ConfirmPassword)
            {
                ErrorMessage = "两次输入的密码不一致";
                return;
            }

            try
            {
                IsBusy = true;
                ClearError();

                var success = await ApiService.RegisterAsync(Username, Password, Nickname);
                if (success)
                {
                    // 注册成功后返回登录页
                    _navigationService.GoBack();
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "注册失败：" + ex.Message;
            }
            finally
            {
                IsBusy = false;
            }
        }

        [RelayCommand]
        private void NavigateBack()
        {
            _navigationService.GoBack();
        }
    }
} 